<?php

namespace Rjyst\RjPdfApi\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class InstallCommand extends Command
{
    protected $signature = 'rj-pdf-api:install {--force : Force install without confirmation}';
    protected $description = 'Install RjYst PDF API Package';

    public function handle()
    {
        $this->info('🚀 开始安装 RjYst PDF API 扩展包...');

        // 1. 检查依赖扩展包
        if (!$this->checkDependencies()) {
            return;
        }

        // 2. 发布API控制器
        $this->publishController();

        // 3. 更新API路由
        $this->updateApiRoutes();

        $this->info('🎉 RjYst PDF API 扩展包安装完成！');
        $this->showNextSteps();
    }

    protected function checkDependencies()
    {
        $this->info('检查依赖扩展包...');

        $dependencies = [
            'App\Models\Category\Category' => [
                'name' => '意识听年级管理扩展包',
                'install_command' => 'php artisan category:install'
            ],
            'App\Models\Category\CategoryModule' => [
                'name' => '意识听分类模块管理扩展包',
                'install_command' => 'php artisan rj-category-module:install'
            ],
            'App\Models\Pdf\PdfImage' => [
                'name' => '意识听PDF管理扩展包',
                'install_command' => 'php artisan rj-pdf:install'
            ],
            'App\Models\Pdf\TextbookRead' => [
                'name' => '意识听教材点读管理扩展包',
                'install_command' => 'php artisan rj-pdf:install'
            ],
            'App\Models\Tool\FileUrl' => [
                'name' => '意识听文件地址管理扩展包',
                'install_command' => 'php artisan file-url:install'
            ]
        ];

        $missingDependencies = [];

        foreach ($dependencies as $class => $info) {
            if (!class_exists($class)) {
                $this->error("❌ 缺少依赖: {$info['name']}");
                $this->line("请先运行: {$info['install_command']}");
                $missingDependencies[] = $info['name'];
            } else {
                $this->info("✅ 依赖检查通过: {$info['name']}");
            }
        }

        // 检查 apiResponse 函数
        if (!function_exists('apiResponse')) {
            $this->error('❌ 缺少依赖: API调用组件库 (apiResponse 函数)');
            $this->line('请先运行: php artisan api-invoke:install');
            $missingDependencies[] = 'API调用组件库';
        } else {
            $this->info('✅ 依赖检查通过: API调用组件库');
        }

        // 检查助手函数
        if (!function_exists('convert_file_address_exist')) {
            $this->warn('⚠️  convert_file_address_exist 函数不存在，请确保相关扩展包已安装');
        } else {
            $this->info('✅ 依赖检查通过: 文件地址转换函数');
        }

        if (!empty($missingDependencies)) {
            $this->error('请先安装依赖扩展包后再继续！');
            return false;
        }

        return true;
    }

    protected function publishController()
    {
        $this->info('发布API控制器...');

        $controllerPath = app_path('Http/Controllers/Api/Pdf/PdfController.php');

        if (File::exists($controllerPath) && !$this->option('force')) {
            $this->info('✅ PdfController 已存在，跳过');
        } else {
            // 确保目录存在
            $controllerDir = app_path('Http/Controllers/Api/Pdf');
            if (!File::isDirectory($controllerDir)) {
                File::makeDirectory($controllerDir, 0755, true);
            }

            $this->call('vendor:publish', ['--tag' => 'rj-pdf-api-controllers', '--force' => $this->option('force')]);
            $this->info('✅ PdfController 创建完成');
        }
    }

    protected function updateApiRoutes()
    {
        $this->info('更新API路由...');

        $routeFile = base_path('routes/api.php');

        if (!File::exists($routeFile)) {
            $this->warn('⚠️  routes/api.php 文件不存在，请先安装 api-invoke 扩展包');
            return;
        }

        $content = File::get($routeFile);

        // 检查是否已包含 PdfController 路由
        if (strpos($content, 'PdfController') !== false) {
            $this->info('✅ PdfController 路由已存在');
            return;
        }

        // 1. 添加 use 语句
        $useStatement = 'use App\Http\Controllers\Api\Pdf\PdfController;';
        if (strpos($content, $useStatement) === false) {
            // 在最后一个 use 语句后添加
            if (preg_match_all('/^use\s+[^;]+;$/m', $content, $matches, PREG_OFFSET_CAPTURE)) {
                $lastUseMatch = end($matches[0]);
                $lastUsePosition = $lastUseMatch[1] + strlen($lastUseMatch[0]);

                $content = substr_replace($content, "\n$useStatement", $lastUsePosition, 0);
            }
        }

        // 2. 添加路由到 v1 分组
        $pdfRoutes = "
    //教材点读-目录
    Route::get('pdf/catalog', [PdfController::class, 'catalog'])
        ->name('pdf.catalog');
    //教材点读-书页
    Route::get('pdf', [PdfController::class, 'pdf'])
        ->name('pdf.pdf');
    //教材点读-朗读
    Route::get('pdf/read', [PdfController::class, 'read'])
        ->name('pdf.read');";

        // 查找 v1 分组的闭合大括号位置
        $lines = explode("\n", $content);
        $newLines = [];
        $inV1Group = false;
        $groupBraceCount = 0;
        $routeAdded = false;

        foreach ($lines as $line) {
            // 检测是否进入 v1 分组
            if (strpos($line, "Route::prefix('v1')->name('api.v1.')") !== false) {
                $inV1Group = true;
                $groupBraceCount = 0;
            }

            if ($inV1Group) {
                // 计算大括号
                $groupBraceCount += substr_count($line, '{') - substr_count($line, '}');

                // 如果遇到分组的结束大括号，在前面添加路由
                if ($groupBraceCount === 0 && strpos($line, '}') !== false && !$routeAdded) {
                    $newLines[] = $pdfRoutes;
                    $routeAdded = true;
                    $inV1Group = false;
                }
            }

            $newLines[] = $line;
        }

        if ($routeAdded) {
            $content = implode("\n", $newLines);
            File::put($routeFile, $content);
            $this->info('✅ 路由添加完成');
        } else {
            $this->warn('⚠️  无法自动添加路由，请手动添加：');
            $this->line($pdfRoutes);
        }
    }

    protected function showNextSteps()
    {
        $this->line('');
        $this->line('<fg=green>🎉 安装完成！功能已就绪：</>');
        $this->line('✅ PdfController API控制器已创建');
        $this->line('✅ API路由已添加到现有路由文件中');
        $this->line('');
        $this->line('<fg=yellow>📋 可用功能：</>');
        $this->line('• 教材点读目录: GET /api/v1/pdf/catalog');
        $this->line('• 教材点读书页: GET /api/v1/pdf');
        $this->line('• 教材点读朗读: GET /api/v1/pdf/read');
        $this->line('• 自动处理图片、音频地址转换');
        $this->line('• 支持坐标点击功能');
        $this->line('• 智能分页功能');
        $this->line('• 统一的JSON响应格式');
        $this->line('');
        $this->line('<fg=blue>🔧 测试接口：</>');
        $this->line('curl -X GET "http://your-domain/api/v1/pdf/catalog?gradeId=1"');
        $this->line('curl -X GET "http://your-domain/api/v1/pdf?gradeId=1&page=1"');
        $this->line('curl -X GET "http://your-domain/api/v1/pdf/read?gradeId=1&page=1"');
        $this->line('');
        $this->line('<fg=blue>🔧 文件位置：</>');
        $this->line('• 控制器: app/Http/Controllers/Api/Pdf/PdfController.php');
        $this->line('• 路由: routes/api.php (已更新)');
        $this->line('');
        $this->line('<fg=red>卸载：</>');
        $this->line('如需卸载扩展包，请运行: <fg=red>php artisan rj-pdf-api:uninstall</>');
    }
}
